import React from 'react'
import Grid from '@material-ui/core/Grid'
import { withStyles, makeStyles } from '@material-ui/core/styles'
import Paper from '@material-ui/core/Paper'
import Typography from '@material-ui/core/Typography'
import TextField from '@material-ui/core/TextField'
import Divider from '@material-ui/core/Divider'
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import FormHelperText from '@material-ui/core/FormHelperText';
import InputLabel from '@material-ui/core/InputLabel';
import Button from '@material-ui/core/Button'

import WelcomPaper from '../welcomPaper';
import axios, { USER_API } from 'API';

const useStyles = makeStyles(theme => ({
  paper: {
    margin: theme.spacing(3, 0, 3, 0),
  },
  divider: {
    margin: theme.spacing(1, 0, 1, 0),
  },
  content: {
    padding: theme.spacing(2),
  },
  paperHeader: {
    fontWeight: "bold",
    padding: theme.spacing(2, 0, 0, 2),
  },
  panelFooter: {
    padding: theme.spacing(0, 0, 1, 1),
  }
}))

function MyPanel(props) {
  const classes = useStyles();
  const footerDivider = props.footer ? (
    <Divider className={classes.divider} />
  ) : null;
  return (
    <Paper className={classes.paper} elevation={3}>
      <Typography variant="h5" className={classes.paperHeader}>{props.title}</Typography>
      <Divider className={classes.divider} />
      <div className={classes.content}>
        {props.children}
      </div>
      {footerDivider}
      <div className={classes.panelFooter}>
        {props.footer}
      </div>
    </Paper>
  )
}

const styles = (theme) => ({
  accountInfo: {
    margin: theme.spacing(1),
  },
  caption: {
    color: theme.palette.secondary.main,
    marginBottom: theme.spacing(1),
  },
  sexSelector: {
    minWidth: 120,
  }
})


class UserInfo extends React.Component {
  constructor(props) {
    super(props);
    const user = this.props.userInfo.user;
    this.handleChange = this.handleChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.sexMapping = {
      '男': 0,
      '女': 1,
      '保密': 2,
    };
    this.state = {
      nickname: user ? user.nickname : "",
      sex: user ? this.sexMapping[user.sex] : "",
      init: user ? true : false,
      error: "",
    };
  }

  componentDidMount() {
    this.props.onTabChange(false);  //更新appbar的状态
  }

  componentDidUpdate() {
    const user = this.props.userInfo.user;
    if (!this.state.init && user) {
      this.setState({
        nickname: user.nickname,
        sex: this.sexMapping[user.sex],
        init: true,
      });
    }
  }

  handleChange(prop) {
    return (event) => {
      this.setState({ [prop]: event.target.value })
    }
  }

  onSubmit() {
    const sexDiff = this.state.sex !== this.sexMapping[this.props.userInfo.user.sex];
    const nicknameDiff = this.state.nickname !== this.props.userInfo.user.nickname;
    if (!sexDiff && !nicknameDiff) {
      this.setState({ error: "请至少修改一项用户信息" });
      return;
    }
    axios.request({
      url: USER_API.update.url,
      method: USER_API.update.method,
      data: {
        sex: this.state.sex,
        nickname: this.state.nickname,
      }
    }).then(response => {
      this.props.setUserInfo(response.data, "userUpdate");
      this.setState({ error: "" });   //清除错误信息
    }).catch(error => {
      let errorMessage = "";
      for (const key in error.response.data) {
        errorMessage += error.response.data[key];
      }
      this.setState({ error: errorMessage });
    })
  }

  renderError() {
    if (this.state.error) {
      return (
        <Typography color="secondary">
          {this.state.error}
        </Typography>
      )
    } else {
      return null;
    }
  }

  renderAccountInfo() {
    const { classes } = this.props;
    return (
      <React.Fragment>
        <TextField
          id="account-email"
          label="邮箱"
          value={this.props.userInfo.user ? this.props.userInfo.user.email : ""}
          variant="outlined"
          className={classes.accountInfo}
          InputProps={{ readOnly: true }}
          helperText="只读信息"
        />
        <TextField
          id="account-nickname"
          label="昵称"
          value={this.state.nickname}
          onChange={this.handleChange('nickname')}
          variant="outlined"
          className={classes.accountInfo}
          helperText="该信息可以修改"
        />
        <FormControl className={`${classes.accountInfo} ${classes.sexSelector}`}>
          <InputLabel>性别</InputLabel>
          <Select
            labelId="sex-select-helper-label"
            id="sex-select-helper"
            value={this.state.sex}
            onChange={this.handleChange('sex')}
          >
            <MenuItem value={0}>男</MenuItem>
            <MenuItem value={1}>女</MenuItem>
            <MenuItem value={2}>保密</MenuItem>
          </Select>
          <FormHelperText>该信息可以修改</FormHelperText>
        </FormControl>
      </React.Fragment>
    )
  }

  renderOtherInfo() {
    const user = this.props.userInfo.user;
    const { classes } = this.props;
    if (!user) {
      // 用户信息不存在，返回空
      return null;
    }
    const lastLoginTime = user.last_login ? (
      <TextField
        id="account-last-login-time"
        label="上次登陆时间"
        value={user ? user.last_login : ""}
        variant="outlined"
        fullWidth
        className={classes.accountInfo}
        InputProps={{ readOnly: true }}
      />
    ) : null;
    const lastActiveIP = user.last_active_ip ? (
      <TextField
        id="account-last-login-ip"
        label="上次登陆ip"
        value={user ? user.last_active_ip : ""}
        variant="outlined"
        fullWidth
        className={classes.accountInfo}
        InputProps={{ readOnly: true }}
      />
    ) : null;
    return (
      <React.Fragment>
        {lastLoginTime}
        {lastActiveIP}
      </React.Fragment>
    )
  }

  render() {
    const { classes } = this.props;
    return (
      <Grid container>
        <Grid item xs={12}>
          <WelcomPaper title="个人中心" description="康康自己的信息" />
        </Grid>
        <Grid item xs={1} sm={2} />
        <Grid item xs={10} sm={8}>
          <MyPanel title="我的账号"
            footer={
              <Button color="primary" variant="contained" onClick={this.onSubmit}>保存</Button>
            }>
            {this.renderAccountInfo()}
            {this.renderError()}
          </MyPanel>
          <MyPanel title="其他信息">
            {this.renderOtherInfo()}
          </MyPanel>
        </Grid>
        <Grid item xs={1} sm={2} />
      </Grid>
    )
  }
}

export default withStyles(styles, { withTheme: true })(UserInfo);